<template>
  <div class="dashboard-container">
    <div class="top">
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="item" @click="handleRouter">
            <div class="left">
               <i class="el-icon-circle-plus-outline" style="font-size: 35px; color: #fff;"></i>
            </div>
            <div class="right">
              <p class="title">创建评估</p>
              <p class="desc">实时便捷，快的不止一点</p>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <div class="content">
      <div class="title">
        任务列表
        <div class="right">
          <el-input placeholder="项目名称" v-model="params.name" size="mini" clearable style="width: 100px;margin-right: 5px;"></el-input>
          <el-input placeholder="编号" v-model="params.serialNumber" size="mini" clearable style="width: 100px;margin-right: 5px;"></el-input>
          <el-select v-model="params.status" placeholder="状态" size="mini" clearable style="width: 100px;margin-right: 5px;">
            <el-option v-for="item in STATUS_TYPE_LIST" :label="item.label" :key="item.value" :value="item.value"></el-option>
          </el-select>
          <el-select v-model="params.inquiryType" placeholder="询价类型" size="mini" clearable style="width: 100px;margin-right: 5px;">
            <el-option v-for="item in typeNameList" :label="item.label" :key="item.value" :value="item.value"></el-option>
          </el-select>
          <el-button type="primary" icon="el-icon-search" plain size="mini" @click="getData">查询</el-button>
          <el-button type="primary" icon="el-icon-search" plain size="mini" @click="handleExport">导出</el-button>
        </div>
      </div>
      <el-table :data="list" v-loading="loading">
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column label="项目名称" prop="name"></el-table-column>
        <el-table-column label="类型" prop="inquiryType"></el-table-column>
        <el-table-column label="业务类型">
          <template slot-scope="{row}">
            {{ row.customerCompanyBusiness?row.customerCompanyBusiness.name:'无' }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="询价时间"></el-table-column>
        <el-table-column prop="status" label="状态"></el-table-column>
        <el-table-column prop="resultMessage" label="结果"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="{row}">
              <el-button type="text" size="mini" @click="handleSubmit(row)" v-if="row.status=='待提交'">提交询价</el-button>  
              <el-button type="text" size="mini" @click="handleDown(row)" v-if="row.docUrl">下载报告</el-button>  
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="page">
          <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="params.pageIndex+1"
                :page-sizes="[10, 20, 30, 40]"
                :page-size="params.pageCount"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
          </el-pagination>
        </div>
    </div>

     <!-- 询价导出选择字段 -->
      <el-dialog
        title="询价导出"
        :visible="dialogVisibleExport" 
        width="800px" 
        @close="dialogVisibleExport=false" 
        :close-on-click-modal="false"
      >
            <el-form >
                <el-form-item label="询价固定字段" v-if="fiexdFieldList.length>0">
                    <el-checkbox  v-model="checkAllFixed" @change="(val)=>handleCheckAllChange('showFixedFields', val)" >全选</el-checkbox>
                    <el-checkbox-group v-model="params.showFixedFields">
                        <el-checkbox v-for="field in fiexdFieldList" :label="field" :key="field">{{field}}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="询价自定义字段" v-if="customFieldList.length>0">
                    <el-checkbox  v-model="checkAllCustom" @change="(val)=>handleCheckAllChange('showCustomFields', val)" >全选</el-checkbox>
                    <el-checkbox-group v-model="params.showCustomFields">
                        <el-checkbox v-for="field in customFieldList" :label="field" :key="field">{{field}}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="评估对象固定字段" v-if="subjectFixedFieldList.length>0">
                    <el-checkbox  v-model="checkAllSubjectFixed" @change="(val)=>handleCheckAllChange('showSubjectFixedFields', val)" >全选</el-checkbox>
                    <el-checkbox-group v-model="params.showSubjectFixedFields">
                        <el-checkbox v-for="field in subjectFixedFieldList" :label="field" :key="field">{{field}}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="评估对象自定义字段" v-if="subjectCustomFieldsList.length>0">
                    <el-checkbox  v-model="checkAllSubjectCustom" @change="(val)=>handleCheckAllChange('showSubjectCustomFields', val)" >全选</el-checkbox>
                    <el-checkbox-group v-model="params.showSubjectCustomFields">
                        <el-checkbox v-for="field in subjectCustomFieldsList" :label="field" :key="field">{{field}}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <div>
                <el-button type="primary" @click="exportData" >导出</el-button>
                <el-button @click="dialogVisibleExport = false">关闭</el-button>
            </div>
      </el-dialog>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { enquiryGetList } from '@/api/enquiry'
import { inquiryGetList, inquiryInfo, inquirySubmit } from '@/api/inquiry'
import { OSS_BASE_URL, typeNameList, useRightList, STATUS_TYPE_LIST, API_BASE_URL } from '@/utils/common'
import { transfromData, transFormValue } from '@/utils/tools'
import { fieldGetList } from '@/api/field'
import moment from 'moment'
import axios from 'axios'

let fiexdFieldList = ["系统编号","询价类型","客户公司","客户人员","客户公司业务类型","业务机构","业务员","项目名称","询价状态","回价时间","回价人员","城市", "区县", "街道", "社区","经度","纬度","位置地图"]
let subjectFixedFieldList = ["资产类型","名称","描述","面积"]

export default {
  name: 'Dashboard',
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  data(){
    return {
      API_BASE_URL,
      STATUS_TYPE_LIST,
      typeNameList,
      useRightList,
      list: [],
      total: 0,
      params: {
        pageCount: 10,
        pageIndex: 0,
        customerCompanyBusinessEiid: '',
        cityId: '',
        inquiryType: '',
        name: '',
        serialNumber: '',
        status: ''
      },
      OSS_BASE_URL,
      typeNameList,
      loading: false,
      // 询价导出字段
      dialogVisibleExport: false,
      fiexdFieldList,
      subjectFixedFieldList,
      subjectCustomFieldsList: [], // 按理自定义字段列表
      customFieldList: [], //询价自定义字段列表
      checkAllFixed: false,
      checkAllSubjectFixed: false,
      checkAllCustom: false,
      checkAllSubjectCustom: false
    }
  },
  async mounted(){
    this.handleSearch();

    //拿询价字段列表
    let xunjia = await fieldGetList({ objectType: 11, pageCount: 999 }); // 查询所有询价模板字段
    let subject = await fieldGetList({ objectType: 8, pageCount: 999 }); // 查询所有评估对象模板字段
    //解析字段
    this.subjectCustomFieldsList = subject.list.map(item=>item.name)
    this.subjectCustomFieldsList = [...new Set(this.subjectCustomFieldsList)] //对数组去重
    this.customFieldList = xunjia.list.map(item=>item.name)
    this.customFieldList = [...new Set(this.customFieldList)] //对数组去重
  },
  methods: {
    //全选按钮
    handleCheckAllChange(name, val) {
        if(name=='showFixedFields'){
            this.params.showFixedFields = val ? this.fiexdFieldList : [];
        }
        if(name=='showSubjectFixedFields'){
            this.params.showSubjectFixedFields = val ? this.subjectFixedFieldList : [];
        }

        if(name=='showCustomFields'){
            this.params.showCustomFields = val ? this.customFieldList : [];
        }

        if(name=='showSubjectCustomFields'){
            this.params.showSubjectCustomFields = val ? this.subjectCustomFieldsList : [];
        }
    },
    //点击导出
    handleExport(){
      // 初始化参数
      this.dialogVisibleExport = true
      this.checkAllFixed = false,
      this.checkAllSubjectFixed = false,
      this.checkAllCustom = false,
      this.checkAllSubjectCustom = false
      this.params.showCustomFields =  []
      this.params.showFixedFields=[]
      this.params.showSubjectCustomFields=[]
      this.params.showSubjectFixedFields=[]
    },
    //导出询价
    exportData(){
      let params = JSON.parse(JSON.stringify(this.params))
        axios({
                url: `${API_BASE_URL}/inquiry/export${transFormValue(params)}`,
                method: 'POST',
                responseType: 'blob'
        }).then((res) => {
                const blob = res.data
                const fileName = moment().format('YYYY-MM-DD') +'询价列表.xlsx'
                const elink = document.createElement('a')
                elink.download = fileName
                elink.style.display = 'none'
                elink.href = window.URL.createObjectURL(blob)
                document.body.appendChild(elink)
                elink.click()
                window.URL.revokeObjectURL(elink.href)// 释放对象
                document.body.removeChild(elink)// 移除元素
      })
    },
    //提交询价
    async handleSubmit(row){
      await inquirySubmit({ id: row.id })
      this.$message.success({ message: '提交成功' })
      this.getData();
    },
    // 下载
    async handleDown(row) {
            return fetch(OSS_BASE_URL+row.docUrl).then(response=>{
                if(!response.ok){
                    throw new Error('network not ok')
                }
                return response.blob();
            }).then(blob=>{
                const url = window.URL.createObjectURL(blob);
                const elink = document.createElement('a')
                elink.style.display = 'none'
                elink.href = url;
                elink.download = row.name + '工业不动产询价单.docx'
                document.body.appendChild(elink)
                elink.click()
                window.URL.revokeObjectURL(elink.href)// 释放对象
                document.body.removeChild(elink)// 移除元素

            }).catch(error=>{
                console.log('error', error)
            })
    },
    handleSearch(){
      this.params.pageIndex = 0;
      this.getData();
    },
    // 修改每页数量
    handleSizeChange(val){
        this.params.pageIndex = 0;
        this.params.pageCount = val;
        this.getData();
    },
    // 切换分页
    handleCurrentChange(val){
        this.params.pageIndex = val - 1;
        this.getData();
    },
    async getData(){
      this.loading = true;
      let data = await inquiryGetList(this.params);
      this.loading = false;
      this.total = data.totalCount;
      this.list = data.list.map(item=>{
        item.createTime = moment(item.createTime).format('YYYY-MM-DD HH:mm:ss')
        item.status = transfromData(STATUS_TYPE_LIST, item.status)
        item.inquiryType = transfromData(typeNameList, item.inquiryType)
        return item;
      });
    },
    handleRouter(){
      this.$router.history.push({ path: '/enquiry/add' })
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    padding: 30px;
    background: #f7fafa;
    .top{
      .item{
        height: 128px;
        background: #41DCED url('../../images/home_icon1.png') no-repeat;
        background-position: calc(100% - 20px);

        border-radius: 10px;
        overflow: hidden;
        cursor: pointer;
        .left{
          display: inline-block;
          width: 60px;
          vertical-align: top;
          padding-top: 40px;
          padding-left: 20px;
        }
        .right{
          display: inline-block;
          text-align: left;
          color: #fff;
          .title{
            font-size: 24px;
            font-weight: bold;
            margin: 0;
            padding-top: 40px;
          }
          .desc{
            font-size: 14px;
          }
        }
      }
    }
    .content{
      padding: 20px;
      border-radius: 5px;
      margin-top: 20px;
      background:#fff;
      .title{
        font-weight: bold;
        .right{
          float: right;
          // padding-top: 40px;
          margin-right: 30px;
          font-weight: normal;
          text-align: right;
        }
      }
      .page{
        padding: 20px 0;
        text-align: center;
      }
    }
  }
  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
</style>
